<template>
	<view class="uni-header">
		<label>
			店铺管理 / 修改店铺
		</label>
	</view>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind" :label-width="150">
			<uni-forms-item name="title" label="店铺名称" required>
				<uni-easyinput placeholder="店铺名称最少为2个汉字，最多为30个汉字，不要使用特殊字符" v-model="formData.title"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="categories" label="店铺分类" required>
				<uni-data-picker placeholder="请选择店铺分类,务必确保正确" v-model="formData.categories"
					collection="opendb-mall-categories" orderby="sort asc"
					field="_id as value, name as text"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="region" label="店铺地址" required>
				<uni-data-picker self-field="code" placeholder="请选择店铺地址" parent-field="parent_code"
					v-model="formData.region" collection="opendb-city-china" orderby="value asc"
					field="code as value,name as text,eq(type,2) as isleaf"></uni-data-picker>
			</uni-forms-item>

			<view class="add-shop-map">
				<iframe id="mapPage" width="100%" height="100%" frameborder=0
					src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=ABIBZ-RGUC4-4DRU5-DRSD4-G5KQE-TOFTY&referer=myapp">
				</iframe>
			</view>
			<uni-forms-item name="address" label="详细地址" required>
				<uni-easyinput disabled placeholder="请在地图中搜索地址,本输入框会自动获取" v-model="formData.address"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="location" label="坐标" required>
				<uni-easyinput disabled placeholder="请在地图中搜索地址,本输入框会自动获取" v-model="formData.location"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="poiname" label="地标名称" required>
				<uni-easyinput disabled placeholder="请在地图中搜索地址,本输入框会自动获取" v-model="formData.poiname"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			
			<uni-forms-item name="area" label="所属区域" required>
				 <uni-data-picker :localdata="area" v-model="formData.area_all" popup-title="请选择区域" @change="onchangeArea"></uni-data-picker>
			</uni-forms-item>
			
			
			<uni-forms-item name="start_business_hours1" label="开始营业时间段1" required>
				<picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺开始营业时间"
					type="number" @change="binddata('start_business_hours1', $event.detail.value)"
					v-model="formData.start_business_hours1">
					<view v-if="formData.start_business_hours1">{{formData.start_business_hours1}}<label
							style="color:#4d85ff;margin-left:10px;">修改</label></view>
					<view v-else>
						<view class="select-business-time">
							+ 点击选择时间
						</view>
					</view>
				</picker>
				<label @click="removeTime('start_business_hours1')" style="cursor:pointer;" title="清除时间">
					<uni-icons type="refresh-filled" size="25" color="#999"></uni-icons>
				</label>
			</uni-forms-item>
			<uni-forms-item name="end_business_hours1" label="结束营业时间段1" required>
				<picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺结束营业时间"
					type="number" @change="binddata('end_business_hours1', $event.detail.value)"
					v-model="formData.end_business_hours1">
					<view v-if="formData.end_business_hours1">{{formData.end_business_hours1}}<label
							style="color:#4d85ff;margin-left:10px;">修改</label></view>
					<view v-else>
						<view class="select-business-time">
							+ 点击选择时间
						</view>
					</view>
				</picker>

			</uni-forms-item>

			<uni-forms-item name="start_business_hours2" label="开始营业时间段2">
				<picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺开始营业时间"
					type="number" @change="binddata('start_business_hours2', $event.detail.value)"
					v-model="formData.start_business_hours2">
					<view v-if="formData.start_business_hours2">{{formData.start_business_hours2}} <label
							style="color:#4d85ff;margin-left:10px;">修改</label></view>
					<view v-else>
						<view class="select-business-time">
							+ 点击选择时间
						</view>
					</view>
				</picker>
				<label @click="removeTime('start_business_hours2')" style="cursor:pointer;" title="清除时间">
					<uni-icons type="refresh-filled" size="25" color="#999"></uni-icons>
				</label>
			</uni-forms-item>

			<uni-forms-item name="end_business_hours2" label="结束营业时间段2">
				<picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺结束营业时间"
					type="number" @change="binddata('end_business_hours2', $event.detail.value)"
					v-model="formData.end_business_hours2">
					<view v-if="formData.end_business_hours2">{{formData.end_business_hours2}}<label
							style="color:#4d85ff;margin-left:10px;">修改</label></view>
					<view v-else>
						<view class="select-business-time">
							+ 点击选择时间
						</view>
					</view>
				</picker>

			</uni-forms-item>
			<uni-forms-item name="logo" label="店铺logo(200*200)" required>
				<uni-file-picker file-mediatype="image" file-extname="jpg,png,gif" return-type="object"
					v-model="formData.logo"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="photo" label="店铺照片(尺寸无限制,系统会自动缩略)" required>
				<uni-file-picker file-mediatype="image" file-extname="jpg,png,gif" :limit="50" return-type="array"
					v-model="formData.photo"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="tel" label="手机号码">
				<uni-easyinput v-model="formData.tel" placeholder="请数据店铺联系手机号码,客户会通过此手机联系商家" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="start_delivery_price" label="起送费">
				<uni-easyinput v-model="formData.start_delivery_price" placeholder="请输入起送费,客户购买需满足该金额才能配送"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="delivery_price" label="配送费">
				<uni-easyinput v-model="formData.delivery_price" placeholder="请输入配送费,添加商品时会默认采用此配送费"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="pack_price" label="打包费">
				<uni-easyinput v-model="formData.pack_price" placeholder="请输入打包费,添加商品时会默认采用此打包费"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="intro" label="简介" required>
				<uni-easyinput type="textarea" maxlength="2000" placeholder="请输入店铺简介,2000字以内" v-model="formData.intro"
					trim="both"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item name="intro" label="关键词(必须以'|'分割)" required>
				<uni-easyinput type="textarea" maxlength="5000" placeholder="请输入店铺关键词,以'|'分割" v-model="keywords"
					trim="both"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item name="preferential" label="满减优惠">
				<view class="preferential-box" v-for="(item,index) in formData.preferential">
					<label>
						满
					</label>
					<label>
						<uni-easyinput style="width:120px;" type="number" placeholder="满足金额"
							v-model="formData.preferential[index].full"></uni-easyinput>
					</label>
					<label>
						元
					</label>
					<label>
						减
					</label>
					<label>
						<uni-easyinput style="width:120px;" type="number" placeholder="减去金额"
							v-model="formData.preferential[index].reduce"></uni-easyinput>
					</label>
					<label>
						元
					</label>
					<label class="goods-add-sku-del" @click="delPreferential(index)">
						删除
					</label>

				</view>
				<view class="preferential-add" @click="addPreferential">
					增加一项满减优惠
				</view>
			</uni-forms-item>
			<uni-forms-item name="is_book" label="暂停营业">
				<uni-data-select
					v-model="pauseDuration"
					:localdata="pauseList"
					@change="selectPause"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="is_book" label="提前预订">
				<switch @change="binddata('is_book', $event.detail.value)" :checked="formData.is_book"></switch>
			</uni-forms-item>
			<uni-forms-item name="is_take_away" label="可否外卖">

				<switch @change="binddata('is_take_away', $event.detail.value)" :checked="formData.is_take_away"></switch>
			</uni-forms-item>
			<uni-forms-item name="disabled_status" label="店铺状态" v-if="isPower(['admin'])">
				<switch @change="binddata('disabled_status', $event.detail.value)" :checked="formData.disabled_status">
				</switch>
			</uni-forms-item>

			<uni-forms-item name="business_status" label="经营状态">
				<switch @change="binddata('business_status', $event.detail.value)" :checked="formData.business_status">
				</switch>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>

		<u-datetime-picker :show="startTime1Show" v-model="formData.start_business_hours1"
			mode="datetime"></u-datetime-picker>
	</view>
</template>
<script>
	import {
		validator
	} from '../../../js_sdk/validator/shop.js';
	import Util from "@/js_sdk/validator/util.js"
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'shop';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	function numberRange(start, end) {
		return Array.from(new Array(end + 1).keys()).slice(start);
	}

	export default {
		data() {
			let formData = {
				"area":null,
				"area_all":[],
				"title": "",
				"categories": "",
				"region": "",
				"address": "",
				"location": "",
				"poiname": "",
				"start_business_hours1": null,
				"end_business_hours1": null,
				"start_business_hours2": null,
				"end_business_hours2": null,
				"logo": null,
				"photo": [],
				"tel": "",
				"start_delivery_price": '',
				"delivery_price": 0,
				"pack_price": 0,
				"intro": "",
				"preferential": [],
				"is_book": '',
				"is_take_away": '',
				"disabled_status": true,
				"business_status": true,
				"create_uid": '',
				"pause_duration":0
			}
			return {
				formData,
				area:[],
				keywords: '',
				formOptions: {
					"score_data": numberRange(0, 5),
					"score_index": null
				},
				rules: {
					...getValidator(Object.keys(formData))
				},
				pauseDuration:0,
				pauseList: [
					{ text: '正常营业', value: 0 },
					{ text: '暂停一天', value: 1 },
					{ text: '暂停两天', value: 2 },
					{ text: '暂停三天', value: 3 },
					{ text: '暂停四天', value: 4 },
					{ text: '暂停五天', value: 5 },
					{ text: '暂停六天', value: 6 },
					{ text: '暂停七天', value: 7 },
				]
			}
		},
		onLoad(e) {
			var that = this;
			uni.getStorage({
				key: 'uni-id-pages-userInfo',
				success: function(res) {
					that.formData.create_uid = res.data._id;
				}
			})
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			var that = this;
			window.addEventListener('message', function(event) {
				// 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
				var loc = event.data;
				if (loc && loc.module == 'locationPicker') { //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
					that.formData.address = loc.poiaddress;
					that.formData.location = new db.Geo.Point(loc.latlng.lng, loc.latlng.lat);
					that.formData.poiname = loc.poiname;
				}
			}, false);
			this.$refs.form.setRules(this.rules)
			this.getArea();
		},
		methods: {
			//设置区域
			onchangeArea(e){
				this.formData.area_all = e.detail.value;
				this.formData.area = e.detail.value[e.detail.value.length - 1];
			},
			//获取配送区域
			getArea(){
			 db.collection('region_city').get().then(res=>{
				 this.area = res.result.data;
			 });
			  
			},
			//删除营业时间
			removeTime(type) {

				if (type == 'start_business_hours1') {
					this.formData.start_business_hours1 = '';
					this.formData.end_business_hours1 = '';
				} else if (type == 'start_business_hours2') {
					this.formData.start_business_hours2 = '';
					this.formData.end_business_hours2 = '';
				}
			},
			binddata(field, e) {
				switch (field) {
					case 'start_business_hours1':
						this.formData.start_business_hours1 = e;
						break;
					case 'end_business_hours1':
						this.formData.end_business_hours1 = e;
						break;
					case 'start_business_hours2':
						this.formData.start_business_hours2 = e;
						break;
					case 'end_business_hours2':
						this.formData.end_business_hours2 = e;
						break;
					case 'disabled_status':
						this.formData.disabled_status = e;
						break;
					case 'business_status':
						this.formData.business_status = e;
						break;
				}
			},
			//删除一项满减优惠
			delPreferential(index) {
				this.formData.preferential.splice(index, 1);
			},
			//增加一项满减优惠
			addPreferential() {
				if (this.formData.preferential) {
					this.formData.preferential.push({
						"full": '',
						"reduce": ''
					});
				} else {
					this.formData.preferential = [{
						"full": '',
						"reduce": ''
					}]
				}
			},
			pickerChange(e, name) {
				this.formOptions[name + '_index'] = e.detail.value;
				this.formData[name] = this.formOptions[name + '_data'][e.detail.value];
				this.binddata(name, this.formData[name]);
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					res.preferential = this.formData.preferential;
					if (res.start_business_hours1) {
						res.start_business_hours1 = this.formData.start_business_hours1.substr(0, 2) + '' + this.formData
							.start_business_hours1.substr(3, 2);
						res.end_business_hours1 = this.formData.end_business_hours1.substr(0, 2) + '' + this.formData
							.end_business_hours1.substr(3, 2);
						if (res.start_business_hours1 > res.end_business_hours1) {
							uni.showToast({
								title: '开始时间不能大于结束时间',
								duration: 2000,
								icon: 'error'
							});
							return false;
						}
					}


					if (res.start_business_hours2) {
						res.start_business_hours2 = this.formData.start_business_hours2.substr(0, 2) + '' + this.formData
							.start_business_hours2.substr(3, 2);
						res.end_business_hours2 = this.formData.end_business_hours2.substr(0, 2) + '' + this.formData
							.end_business_hours2.substr(3, 2);
						if (res.start_business_hours2 > res.end_business_hours2) {
							uni.showToast({
								title: '开始时间不能早于结束时间',
								duration: 2000,
								icon: 'error'
							});
							return false;
						}

						if (res.start_business_hours2 < res.end_business_hours1) {
							uni.showToast({
								title: '时间2不能早于时间1',
								duration: 2000,
								icon: 'error'
							});
							return false;
						}
					}
					//配送费，起送费和打包费乘以100
					res.start_delivery_price = res.start_delivery_price * 100;
					res.delivery_price = res.delivery_price * 100;
					res.pack_price = res.pack_price * 100;
					//讲关键词转化为数组
					res.keywords = this.keywords.split("|");
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			// 暂停营业
			selectPause(e){
				console.log(e)
				this.pauseDuration = e
				let time = this.formData.start_business_hours1.substring(0,2)
				let temp = Util.getTimestampAfter(e,time)
				this.formData.pause_duration = temp
			},
			/**
			 * 提交表单
			 */
			submitForm(value) {
				value.area_all = this.formData.area_all;
				value.pause_duration = this.formData.pause_duration
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"title,categories,region,address,location,poiname,pause_duration,start_business_hours1,area,area_all,end_business_hours1,start_business_hours2,end_business_hours2,logo,photo,tel,start_delivery_price,delivery_price,pack_price,intro,preferential,is_book,is_take_away,keywords,disabled_status,business_status"
					).get().then((res) => {
					const data = res.result.data[0]
					this.pauseDuration = data.pause_duration? Util.getDaysAfter(data.pause_duration) : 0
					if (data) {
						if (data.start_business_hours1) {
							data.start_business_hours1 = data.start_business_hours1.substr(0, 2) + ':' + data
								.start_business_hours1.substr(2, 2);
						}
						if (data.start_business_hours2) {
							data.start_business_hours2 = data.start_business_hours2.substr(0, 2) + ':' + data
								.start_business_hours2.substr(2, 2);
						}

						if (data.end_business_hours1) {
							data.end_business_hours1 = data.end_business_hours1.substr(0, 2) + ':' + data
								.end_business_hours1.substr(2, 2);
						}
						if (data.start_business_hours2) {
							data.end_business_hours2 = data.end_business_hours2.substr(0, 2) + ':' + data
								.end_business_hours2.substr(2, 2);
						}
						//配送费，起送费和打包费乘以100
						data.start_delivery_price = data.start_delivery_price / 100;
						data.delivery_price = data.delivery_price / 100;
						data.pack_price = data.pack_price / 100;
						//把关键词转化为以|分割的字符串
						if (data.keywords) {
							this.keywords = data.keywords.join('|')
						}

						this.formData = data

						for (let key in this.formOptions) {
							let pickerIndex = key.lastIndexOf("_index")
							if (pickerIndex > -1) {
								let fieldName = key.substring(0, pickerIndex)
								let fieldData = this.formOptions[fieldName + "_data"];
								if (data[fieldName] && fieldData && fieldData.indexOf(data[fieldName]) > -1) {
									this.formOptions[fieldName + "_index"] = fieldData.indexOf(data[fieldName])
								}
							}
						}
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			isPower(admin=['']){
				return Util.userHasPermission(admin)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.preferential-add {
		float: left;
		width: 100%;
		height: 30px;
		line-height: 30px;
		text-align: center;
		background: rgba(240, 240, 240, .3);
		color: #e7c000;
		margin-bottom: 20px;
		font-size: 13px;
		cursor: pointer;
		border: 1px solid #e7c000;
		margin-top: 30px;
	}

	.preferential-box label {
		float: left;
		line-height: 35px;
		margin-right: 20px;
	}

	.preferential-box {
		width: 100%;
		float: left;
		margin-bottom: 10px;
	}

	.select-business-time-picker {
		margin-top: 8px;
		font-size: 15px;
	}

	.select-business-time {
		width: 120px;
		color: #666;
		line-height: 30px;
		border: 1px solid #666;
		text-align: center;
		border-radius: 3px;
	}

	.add-shop-map {
		height: 500px;
		margin-bottom: 50px;
		background: #f4f4f4;
		padding: 20px;
	}
</style>